import { Injectable } from '@nestjs/common';
import { CreateAuthDto } from './dto/create-auth.dto';
import { UpdateAuthDto } from './dto/update-auth.dto';
import { InjectRepository } from '@nestjs/typeorm';
import * as bcryptjs from 'bcryptjs';
import { JwtService } from '@nestjs/jwt';
import { Repository } from 'typeorm';
import { AuthEntity } from './entities/auth.entity';
import { BadRequestException } from '@nestjs/common';

@Injectable()
export class AuthService {
  // 使用InjectRepository装饰器并引入Repository这样就可以使用typeorm的操作了
  constructor(
    @InjectRepository(AuthEntity)
    private readonly authRepository: Repository<AuthEntity>,
    private readonly JwtService: JwtService,
  ) {}

  create(createAuthDto: CreateAuthDto) {
    return 'This action adds a new auth';
  }
  // 注册
  async signup(signupData: {
    username: string;
    password: string;
    phone: string;
  }): Promise<{
    code: number;
    msg: string;
  }> {
    const data = await this.authRepository.query(
      'SELECT COUNT(1) AS count  FROM db_book.book_user WHERE username = ?',
      [signupData.username],
    );
    let status = data && data[0]['count'] == 0;
    const code = status ? 200 : 409;
    const msg = status ? '注册成功' : '用户已存在';
    // 对密码进行加密处理
    if (status) {
      signupData.password = bcryptjs.hashSync(signupData.password, 10);
      await this.authRepository.query(
        'INSERT INTO book_user (username, password,phone) VALUES (?,?,?)',
        [signupData.username, signupData.password, signupData.phone],
      );
    }
    return { code, msg };
  }

  // 登录
  async login(loginData: { username: string; password: string }) {
    const findUser = await this.authRepository.query(
      'SELECT * FROM book_user WHERE username = ?',
      [loginData.username],
    );
    const data = { ...findUser[0] };

    console.log(data);

    // 没有找到
    if (!data.username || loginData.username != data.username)
      return new BadRequestException('用户不存在');
    // 找到了对比密码
    const compareRes: boolean = bcryptjs.compareSync(
      loginData.password,
      data.password,
    );
    // 密码不正确
    if (!compareRes) return new BadRequestException('密码不正确');
    const payload = { username: data.username };
    return {
      access_token: this.JwtService.sign(payload),
      msg: '登录成功',
    };
  }
  findAll() {
    return `This action returns all auth`;
  }

  findOne(id: number) {
    return `This action returns a #${id} auth`;
  }

  update(id: number, updateAuthDto: UpdateAuthDto) {
    return `This action updates a #${id} auth`;
  }

  remove(id: number) {
    return `This action removes a #${id} auth`;
  }
}
